package com.my.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.entity.User;
import com.my.entity.UserMonitor;
import com.my.service.UserMonitorService;
import com.my.service.UserService;
import com.my.util.Rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("api")
@CrossOrigin
public class UserMonitorApiController {

    @Autowired
    private UserMonitorService service;

    @Autowired
    private UserService uService;

    @PostMapping("userMonitor/add")
    public Rest add(Long attendance, Long rollCall, Long classId) {
        User aUser = null, rUser = null;
        if(attendance != null) {
            aUser = uService.getById(attendance);
            if(aUser == null) {
                return Rest.err(attendance + " 学号的学生不存在！");
            }
            if(aUser.getGradeClassId() != classId) {
                return Rest.err("指定考勤班长不在该班！");
            }
        }
        if(rollCall != null) {
            rUser = uService.getById(rollCall);
            if(rUser == null) {
                return Rest.err(rollCall + " 学号的学生不存在！");
            }
            if(rUser.getGradeClassId() != classId) {
                return Rest.err("指定晚点班长不在该班！");
            }
        }
        if(aUser != null) {
            service.remove(new QueryWrapper<UserMonitor>().eq("grade_class_id", aUser.getGradeClassId()).eq("type", 1));
            service.save(new UserMonitor().setType(1).setUserId(aUser.getId()).setGradeClassId(aUser.getGradeClassId()));
        }
        if(rUser != null) {
            service.remove(new QueryWrapper<UserMonitor>().eq("grade_class_id", rUser.getGradeClassId()).eq("type", 2));
            service.save(new UserMonitor().setType(2).setUserId(rUser.getId()).setGradeClassId(rUser.getGradeClassId()));
        }
        return Rest.ok("设置成功！");
    }

}
